<template lang="pug">
	p
		a.btn.btn-primary(v-link="{name: 'connections'}") 切换连接
	.panel.panel-default
		.panel-heading
			h3.panel-title 设置连接
		.panel-body
			form.form-horizontal
				mixin group(name, model, help, addon)
					.form-group(
						v-bind:class=`
							{'has-error': !available}
						`
					)
						label.col-sm-2.control-label #{name}
						.col-sm-10
							div(style="width: 75%;")
								mixin input
									input.form-control(
										v-model=`${model}` lazy
										@focus=`this.focusForm = '${model}'`
									)
								mixin list-group
									ul.list-group
										li.list-group-item.small(
											v-for=`item in suggest['${model}'].items`
											@click=`${model} = item.value`
										)
											| {{item.value}}
											i.fa.fa-remove.fa-fw.pull-right(
												@click='item.remove()'
											)
								mixin template
									template(v-if=`focusForm === '${model}' && suggest['${model}'].items.length`)
										block
								if addon
									.input-group
										span.input-group-addon #{addon}
										+input
									+template
										p.small
										.input-group
											span.input-group-addon(style="visibility: hidden;") #{addon}
											+list-group
								else
									+input
									+template
										p.small
										+list-group
							p.help-block #{help}
				+group(
					'主机:',
					'server.host',
					'输入 Aria2 RPC 所在服务器的 IP 或域名（默认：localhost）',
					'http(s)://'
				)
				+group(
					'端口:',
					'server.port',
					'输入 Aria2 RPC 端口号（默认：6800）'
				)
				+group(
					'RPC 路径:',
					'server.path',
					'输入 Aria2 RPC 路径（默认：/jsonrpc）',
					'http(s)://{{host}}:{{port}}'
				)
				+group(
					'刷新时间:',
					'server.refresh',
					'单位为秒，1 => 1s, 5=> 5s'
				)
				.form-group
					label.col-sm-2.control-label
					.col-sm-10
						hr
						p.help-block(v-show="available&&(!promise.isPending())") 连接成功
						p.help-block(v-show="!available&&(!promise.isPending())") 连接失败
						p.help-block(v-show="promise.isPending()") ...连接中

			hr
			div
				button.btn.btn-primary.pull-right(
					@click="submit()"
					v-bind="{disabled: !available}"
				) 
					|保存
					i.fa.fa-spinner.fa-pulse.fa-fw(
						v-show="promise.isPending()"
					)
</template>
<script>
	/*eslint no-magic-numbers: ["error", {"ignore": [1000]}] */
	

	const _ = require('lodash')
	const OptionStore = require('optionStore')
	
	module.exports = {
		mixins: [
			require('mixin/rpc'),
		],
		data () {
			return {
				server: {
					host   : this.$store.state.host,
					port   : this.$store.state.port,
					path   : this.$store.state.path,
					refresh: this.$store.state.refresh,
				},
				available: false,
				promise  : null,
				focusForm: '',
				suggest  : [
					'server.host',
					'server.port',
					'server.path',
					'server.refresh',
				].reduce(
					(acc, name) => Object.assign(acc, {
						[name]: new OptionStore(name),
					}),
					{}
				),
			}
		},
		methods: {
			submit () {
				if (!this.available) return

				if (this.promise && this.promise.isPending()) return

				{
					this.$store.commit('connection', {
						...this.server,
					})

					new OptionStore('server.host')
						.add(this.server.host)
						.save()
					new OptionStore('server.port')
						.add(this.server.port)
						.save()
					new OptionStore('server.path')
						.add(this.server.path)
						.save()

					const v = parseInt(this.server.refresh, 10)

					if (v) this.$store.state.refresh = v
				}

				this.createConnection({
					host: this.server.host,
					port: this.server.port,
					path: this.server.path,
				}).then(() => {
					this.$router.go({
						name: 'index',
					})
				})
			},
			testConnection () {
				return this._api(
					this.server,
					'aria2.getVersion'
				)
			},
		},
		watch: {
			server: {
				handler () {
					if (this.promise) this.promise.cancel()
	

					const fn = res => {
						this.available = !_.isError(res)
					}

					this.$set(
						'promise',
						this.testConnection()
							.timeout(1000)
							.then(fn)
							.catch(fn)
					)
				},
				deep     : true,
				immediate: true,
			},
		},
	}
</script>